import { SettingOutlined } from "@ant-design/icons"
import { Form, Input, Modal, Select, type ModalProps } from "antd"
import type { Rule } from "antd/es/form"
import Password from "antd/es/input/Password"
import useMessage from "antd/es/message/useMessage"
import React, { useEffect, useState } from "react"

import { sendToBackground } from "@plasmohq/messaging"

import { TokenIconData } from "~components/iconData"
import OIModal from "~components/OIModal/OIModal"
import { useTokenStroe } from "~store/tokenStore"
import type { AccessToken, TokenType } from "~type/tokenType"
import { defaultRule, getStyleContainerRoot } from "~util"
import { OIAItype } from "~util/AIUtil"

export default function (params: ModalProps) {
  const [msg, contextHolder] = useMessage({
    getContainer: () => getStyleContainerRoot()
  })
  const tokenType = useTokenStroe((state) => state.tokenType)
  // const apiKey = useTokenStroe((state) => state.apiKey)
  // const secretKey = useTokenStroe((state) => state.secretKey)
  const setReqToken = useTokenStroe((state) => state.setReqToken)
  const setToken = useTokenStroe((state) => state.setToken)
  const [setForm] = Form.useForm<TokenType>()
  const onSubmit = async () => {
    setForm.submit()
  }
  const onFinish = async (values: TokenType) => {
    console.log(values)
    setReqToken(values)
    const { message } = await sendToBackground<TokenType>({
      name: "accessToken",
      body: values
    })
    console.log(message)
    if (message.status == 200) {
      setToken(message.data as AccessToken)
      const e: any = {}
      msg.success(message.msg)
      setTimeout(() => {
        params.onCancel(e)
      }, 500)
    }
  }
  useEffect(() => {
    setForm.setFieldsValue({ ...tokenType })
  }, [tokenType.aiSource, tokenType.secretKey, tokenType.apiKey])
  return (
    <>
      {contextHolder}
      <OIModal
        {...params}
        title={<TokenIconData className="text-lg" />}
        onOk={onSubmit}>
        <div className="p-4">
          <Form
            autoComplete="off"
            name="set"
            form={setForm}
            labelCol={{ span: 6 }}
            labelAlign="right"
            wrapperCol={{ span: 18 }}
            className="w-full"
            onFinish={onFinish}>
            <Form.Item label="AI_Source" name="aiSource" rules={[defaultRule]}>
              <Select
                getPopupContainer={() => getStyleContainerRoot() as any}
                options={OIAItype}
                fieldNames={{ label: "name", value: "type" }}></Select>
            </Form.Item>
            <Form.Item label="API_key" name="apiKey" rules={[defaultRule]}>
              <Input></Input>
            </Form.Item>
            <Form.Item
              label="secret_key"
              name="secretKey"
              rules={[defaultRule]}>
              <Password></Password>
            </Form.Item>
          </Form>
        </div>
      </OIModal>
    </>
  )
}
